
#include    <stdio.h>
#include    <time.h>
#include    <stdarg.h>

#include    "zsocket/udper.hpp"

using namespace std;
using namespace zsocket;

static  const char* now( void )
{
    static  char    szNow[ 64 ];
    
    time_t  t = time(NULL);
    struct tm*  ptm = localtime( &t );
    
    strftime( szNow, sizeof(szNow) - 1, "%Y-%m-%d %H:%M:%S", ptm );
    
    return  szNow;
}

static  void    debug( const char* pszFormat, ... )
{
    va_list args;
    
    va_start( args, pszFormat );
    fprintf( stderr, "%s ", now() );
    vfprintf( stderr, pszFormat, args );
    fprintf( stderr, "\n" );
    va_end( args ); 
}

int     main ( int argc, char* argv[] )
{
    const char* pszAddress = "localhost";   //"127.0.0.1";
    int     iPort = 4344;
    int     iMaxTimes = 100000;
    
    Udper   udper;
    
    udper.open();
    
    Address address( pszAddress, iPort );
    char    szData[ 65536 ];
    unsigned iDataSize = 1024;
    memset( szData, 'A', iDataSize );
    szData[ iDataSize ] = '\0';
    string  request;
    request.assign(szData, iDataSize);
    
    debug( "%s start ...", argv[0] );
    time_t  time_start = time(NULL);
    for( int i=0; i<iMaxTimes; i++ ) {
        //debug( "sending #%d message ...", i + 1 );
        int iReturn;
        try {
            udper.sendto( address, request );
        }
        catch( Exception& ex ) {
            debug( "fail to send : %s", ex.what() );
            --i;
            continue;
        }

        //debug( "recving #%d message ...", i + 1 );
        string  response;
        try {
            udper.recvfrom( address, response );
        }
        catch( Exception& ex ) {
            debug( "fail to recv : %s", ex.what() );
            --i;
            continue;
        }
        if ( request != response ) {
            debug( "BAD ECHO." );
        }
    }
    time_t  time_last = time(NULL) - time_start;
    debug( "%s stop.", argv[0] );
    double  tps = iMaxTimes / time_last;
    debug( "times:%d msg-size:%d time-last:%d tps=%.3f", iMaxTimes, iDataSize, time_last, tps );
    
    udper.close();
    
    return  0;
}


